package com.tencent.qf.common.activityplatform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.common.util.SignatureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;

/**
 * 签到活动平台，接口交互类
 * @author liuxuan
 * @time 2022/12/21 9:51
 */
@Slf4j
@Component
public class ActivityPlatformUtils {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ActivityPlatformApiConfig activityPlatformApiConfig;

    public String post(Object request, String apiPath) {
        HashMap<String, Object> map = JSON.parseObject(JSON.toJSONString(request), new TypeReference<HashMap<String, Object>>() {
        });
        map.put("appkey", activityPlatformApiConfig.getAppKey());
        map.put("time", LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        String sign = SignatureUtils.sign(map, activityPlatformApiConfig.getAppSecret());
        map.put("sign", sign);

        HttpHeaders headers = new HttpHeaders();
        headers.add("appkey",activityPlatformApiConfig.getAppKey());
        headers.add("time",String.valueOf(map.get("time")));
        headers.add("sign",sign);
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(map), headers);
        log.info("请求签到活动平台{} 入参{}", apiPath, JSON.toJSONString(map));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(activityPlatformApiConfig.getUrl() + apiPath, entity, String.class);
        log.info("请求签到活动平台{} 出参{}", apiPath, JSON.toJSONString(responseEntity));
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            String body = responseEntity.getBody();
            return body;
        }
        return null;
    }


}
